package com.bt.framework.manager

import android.app.Activity
import android.app.Application
import android.os.Bundle

/**
 * Created by wsh
 * Date: 2020/9/23
 * Description:App前后台切换监听
 */
object AppFrontBack {

    /**
     * 启动的Activity数量
     */
    private var activityStartCount = 0

    fun register(application: Application, frontBakListener: AppFrontBakListener) {
        application.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(
                activity: Activity,
                savedInstanceState: Bundle?
            ) {

            }

            override fun onActivityStarted(activity: Activity) {
                activityStartCount++
                if (activityStartCount == 1) {
                    frontBakListener.onFront(activity)
                }
            }

            override fun onActivityResumed(activity: Activity) {

            }

            override fun onActivityPaused(activity: Activity) {

            }

            override fun onActivityStopped(activity: Activity) {
                activityStartCount--
                if (activityStartCount == 0) {
                    frontBakListener.onBack(activity)
                }
            }

            override fun onActivitySaveInstanceState(
                activity: Activity,
                outState: Bundle
            ) {

            }

            override fun onActivityDestroyed(activity: Activity) {

            }
        })
    }
}

interface AppFrontBakListener {
    /**
     * 前台
     */
    fun onFront(activity: Activity)

    /**
     * 后台
     */
    fun onBack(activity: Activity)
}